<template>
  <view class="login-container">
    <view class="login-box">
      <image src="/static/logo.png" mode="aspectFit" class="logo" />
      
      <view class="title">欢迎来到大米哥的店</view>
      <view class="subtitle">让生活更有滋味</view>
      
      <button 
        class="wx-login-btn" 
        :disabled="!isAgreed"
        open-type="getPhoneNumber" 
        @getphonenumber="handleGetPhoneNumber"
      >
        <text class="iconfont icon-weixin"></text>
        一键登录
      </button>
      
      <view class="agreement">
        <checkbox-group @change="handleAgreementChange">
          <label class="agreement-label">
            <checkbox :checked="isAgreed" style="transform: scale(0.7)" />
            <text class="agreement-text">
              我已阅读并同意
              <text class="link" @tap="openAgreement('user')">《用户协议》</text>
              和
              <text class="link" @tap="openAgreement('privacy')">《隐私政策》</text>
            </text>
          </label>
        </checkbox-group>
      </view>
    </view>
  </view>
</template>

<script>
import { useUserStore } from '@/store/userStore'

export default {
  data() {
    return {
      redirectUrl: '', // 存储登录后需要跳转的页面
      redirectType: 'navigateTo',
      isAgreed: false // 是否同意用户协议
    }
  },
  setup() {
    const userStore = useUserStore()
    return {
      userStore
    }
  },
  onLoad(options) {
    if (options.redirect) {
      this.redirectUrl = decodeURIComponent(options.redirect)
      this.redirectType = options.type || 'navigateTo'
    }
    this.checkWXSession()
  },
  methods: {
    handleAgreementChange(e) {
      this.isAgreed = e.detail.value.length > 0
    },
    
    openAgreement(type) {
      const url = type === 'user' ? '/pages/agreement/user' : '/pages/agreement/privacy'
      uni.navigateTo({ url })
    },
    
    async checkWXSession() {
      try {
        const { code } = await uni.login({
          provider: 'weixin'
        })
        this.wxCode = code
      } catch (error) {
        uni.showToast({
          title: '微信登录失败，请重试',
          icon: 'none'
        })
      }
    },

    async handleGetPhoneNumber(e) {
      if (!this.isAgreed) {
        uni.showToast({
          title: '请先同意用户协议和隐私政策',
          icon: 'none'
        })
        return
      }

      if (e.detail.errMsg !== "getPhoneNumber:ok") {
        uni.showToast({
          title: '获取手机号失败',
          icon: 'none'
        })
        return
      }

      try {
        const res = await this.userStore.wxLogin({
          code: this.wxCode,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        })

        if (res) {
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          })

          setTimeout(() => {
            if (this.redirectUrl) {
              if (this.redirectType === 'switchTab') {
                uni.switchTab({
                  url: this.redirectUrl
                })
              } else {
                uni.redirectTo({
                  url: this.redirectUrl
                })
              }
            } else {
              uni.switchTab({
                url: '/pages/index/index'
              })
            }
          }, 1500)

          console.log('登录成功，完整响应:', res);
          console.log('保存的token:', res.data.token);
          console.log('存储后的token:', uni.getStorageSync('token'));
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '登录失败',
          icon: 'none'
        })
        this.checkWXSession()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .login-box {
    width: 100%;
    padding: 60rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .logo {
      width: 200rpx;
      height: 200rpx;
      margin-bottom: 40rpx;
    }
    
    .title {
      font-size: 40rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
    }
    
    .subtitle {
      font-size: 28rpx;
      color: #999;
      margin-bottom: 80rpx;
    }
    
    .wx-login-btn {
      width: 100%;
      height: 88rpx;
      background-color: #07c160;
      color: #fff;
      border-radius: 44rpx;
      font-size: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 40rpx;
      
      &:disabled {
        opacity: 0.6;
      }
      
      .iconfont {
        margin-right: 10rpx;
        font-size: 40rpx;
      }
      
      &::after {
        border: none;
      }
    }
    
    .agreement {
      width: 100%;
      
      .agreement-label {
        display: flex;
        align-items: center;
        justify-content: center;
        
        .agreement-text {
          font-size: 24rpx;
          color: #999;
          
          .link {
            color: #07c160;
          }
        }
      }
    }
  }
}
</style>
